define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        uploader = require('js/utils/uploader'),
        app = Backbone.history;

    require('jquery-ui');
    require('magnific');

    var VirtualListView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click a.onClickDelete': 'toDelete',
            'click #search': 'doSearch',
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.VirtualCollection();
            this.collection.bind('change reset remove', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);

            return this;
        },
        doSearch: function () {
            var options = utils.getAllInput("#sidebar_right", true),
                searched = utils.getAllInput('#sidebar_right');
            if (searched.status) {
                options.avatar_id = searched.status ? "$!null" : "$null";
                delete options.status;
            }
            utils.saveSearched('op/virtual', searched);
            app.navigate(utils.composeQueryString('#op/virtual/', options), {
                trigger: true
            });
        },
        toDelete: function (e) {
            utils.deleteItem(e, this.collection);
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/virtual'),
                unused_avatar_count: this.collection.unused_avatar_count
            }));
            var that = this;
            uploader.getFileUploader('/admin/virtual/');
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/virtual/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('#uploadAvatar').magnificPopup({
                items: {
                    src: '#uploadImagePanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                // showCloseBtn: false,
                callbacks: {
                    beforeOpen: function () {
                        var cachedImages = [];
                        uploader.getSimplerUploader('pickfiles', function (url) {
                            cachedImages.push(url);
                            $('#countTip').html('提示：已上传' + cachedImages.length + '个');
                        }, true);
                        uploader.setProcess({
                            max: 0,
                            now: 0
                        });
                        $('#uploadprocess').html('');
                        $('#addCachedImgs').off('click').click(function () {
                            $.magnificPopup.close();
                            $.post('/admin/virtual/avatar/', JSON.stringify({
                                'avatars': cachedImages
                            })).fail(function (data) {
                                notify.notifyResp(data);
                            });
                        });
                    }
                }
            });
            utils.getPaginator(that.options, this.collection.total, '#op/virtual/');

            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/VirtualList.html",

        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new VirtualListView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
    var VirtualDetailView = Backbone.View.extend({
        tagName: "div",
        className: "panel-body pn",
        events: {
            'click #save': 'toSaveOrCreate'
        },
        initialize: function (options) {
            this.model = new models.Virtual();
            if (options.id) {
                this.model.set('id', options.id);
            }
            this.model.bind('change reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        toSaveOrCreate: function (e) {
            e.preventDefault();
            if (!$('#virtual-form').valid()) {
                notify.error('错误', "输入错误，请检验");
                return;
            }
            var avatar_id = $('#avatar').attr('src') || "";
            if (avatar_id.indexOf('placeholder') >= 0) {
                avatar_id = null;
            }
            var attrs = {
                'nick_name': $('#inputNickname').val(),
                'ip': $('#inputIp').val(),
                'avatar_id': avatar_id,
                'phone': $('#inputPhone').val()
            };
            var pattern = /^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$/;
            if (!attrs.ip.match(pattern)) {
                notify.error('错误', 'ip地址格式错误');
                return;
            }
            this.model.save(attrs, {
                patch: true,
                success: function (model, response) {
                    notify.success('提示', '保存成功！');
                    setTimeout(function () {
                        history.back();
                    }, 500);
                },
                error: function (model, response) {
                    notify.notifyResp(response);
                }
            });

            return false;
        },
        renderWithData: function () {
            this.$el.html(this.template({
                info: this.model.toJSON()
            }));
            utils.getValidator('#virtual-form');
            uploader.getSingleUploader('uploadAvatar', false, null, true);
            return this;
        },
        load: function () {
            if (this.model.id) {
                this.model.fetch({
                    reset: true
                });
            } else {
                this.renderWithData();
            }
        }
    });
    exports.Detail = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/VirtualDetail.html",

        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new VirtualDetailView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});